<template>
  <!-- 用户管理 -->
  <div class="main">
    <!-- 面包屑：导航 -->
    <app-link :name="title"></app-link>
    <!-- 搜索表单 -->

    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="手机号/账号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.sex" width="50px" placeholder="性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchall" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="reset" icon="el-icon-refresh-left">重置</el-button>
        <el-button type="primary" @click="addUser" icon="el-icon-document">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" height="430" border style="width: 100% ; ">
      <el-table-column type="index" label="排序" width="50"></el-table-column>
      <el-table-column prop="username" label="账号" width="150"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="sex" label="性别" width="80"></el-table-column>
      <el-table-column prop="age" label="年龄" width="120"></el-table-column>
      <el-table-column prop="address" label="地址" width="220"></el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- v-show="pages >1" -->
    <el-pagination
      v-show="pages >1"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加新用户 -->
    <el-dialog :title="isAdd ? '添加用户' :'编辑用户'" :visible.sync="dialogFormVisible" width="600px">
      <el-form
        :rules="rules"
        :model="ruleForm"
        label-position="right"
        label-width="100px"
        class="demo-ruleForm"
        ref="ruleForm"
      >
        <el-form-item label="手机号/账号" prop="username">
          <el-input
            v-model.trim="ruleForm.username"
            autocomplete="off"
            style="width:300px"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input
            v-model="ruleForm.name"
            autocomplete="off"
            placeholder="请输入姓名"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleForm.sex" placeholder="性别">
            <el-option label="女" value="女"></el-option>
            <el-option label="男" value="男"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="ruleForm.age"
            autocomplete="off"
            placeholder="请输入年龄"
            style="width:300px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input
            v-model="ruleForm.address"
            autocomplete="off"
            style="width:300px"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="isAdd ? add() : edit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import appLink from "@/components/link.vue";
import usersApi from "@/api/usersApi";

export default {
  data() {
    var validatePsw = (rule, value, callback) => {
      let reg = /1[3-9]\d{9}/;
      if (reg.test(value) && value.length == 11) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号码"));
      }
    };
    return {
      title: "用户管理",
      searchForm: {
        name: "",
        sex: ""
      }, //查询条件
      list: [],
      page: 1,
      pagesize: 10,
      total: 0,
      pages: 0,
      dialogFormVisible: false, //弹窗开关

      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" } //真实姓名不能为空
        ],
        username: [
          { required: true, message: "手机号码不能为空", trigger: "blur" }, //用户名不能为空
          { validator: validatePsw, trigger: "blur" } //验证用户名是否存在
        ]
      },
      //表单验证规则
      ruleForm: {
        username: "",
        name: "",
        sex: "",
        age: "",
        address: ""
      },
      uid: "",
      isAdd: true, //对话框类别初始值 true:添加用户
      fileList: []
    };
  },

  components: { appLink },

  methods: {
    //进入页面就发送请求，获取用户列表
    async fetchall() {
      console.log(
        this.page,
        this.pagesize,
        this.searchForm.name,
        this.searchForm.sex
      );
      try {
        let p = await usersApi.getList(
          this.page,
          this.pagesize,
          this.searchForm.name,
          this.searchForm.sex
        );
        console.log(p);
        if (p.data.flag) {
          this.list = p.data.data; //数据部分
          console.log(this.list);
          this.total = p.data.data2; //总条数
          this.pages = p.data.data2;
        } else {
          this.$message({
            message: "找不到数据",
            type: "warnning"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    reset() {
      this.searchForm = {};
    },

    //功能：点击打开弹窗
    addUser() {
      this.isAdd = true; //添加用户，开关设置为true
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["ruleForm"].resetFields();
      });
    },

    //点击打开编辑功能
    editUser(row) {
      this.isAdd = false;
      this.dialogFormVisible = true;
      this.ruleForm = row;
      this.uid = row.uid;
    },

    //修改用户信息
    async edit() {
      console.log(
        this.ruleForm.username,
        this.ruleForm.name,
        this.ruleForm.sex,
        this.ruleForm.age,
        this.ruleForm.address,
        this.uid
      );
      try {
        let p = await usersApi.editUser(
          this.ruleForm.username,
          this.ruleForm.name,
          this.ruleForm.sex,
          this.ruleForm.age,
          this.ruleForm.address,
          this.uid
        );
        if (p.data.flag) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.fetchall();
          this.dialogFormVisible = false; //关闭窗口
        } else {
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    // 添加新用户
    add() {
      this.$refs.ruleForm.validate(async res => {
        if (res) {
          try {
            let p = await usersApi.addUser(
              this.ruleForm.username,
              this.ruleForm.name,
              this.ruleForm.sex,
              this.ruleForm.age,
              this.ruleForm.address
            );
            console.log(p);
            if (p.data.flag) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.fetchall();
              this.dialogFormVisible = false; //关闭窗口
            } else {
              this.$message({
                message: "添加失败",
                type: "error"
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          //校验没通过：不能提交
          this.$message({
            message: "注意书写条件哦",
            type: "error"
          });
        }
      });
    },

    // 删除一个用户
    delUser(row) {
      this.$confirm("此操作将永久删除该用户吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 点击确定：真的删除
          usersApi.delUser(row.uid).then(res => {
            if (res.data.flag) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              // 刷新页面
              this.fetchall();
            } else {
              this.$message({
                message: "删除失败",
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val; //每页多少条
      this.page = 1; //如果切换每页多少条，回到第一页开始看
      this.fetchall();
    },

    // 分页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.fetchall();
    }
  },

  created() {
    this.fetchall(); //进入页面就发起请求
  }
};
</script>

<style scoped>
.el-form {
  margin-top: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 30px;
}
</style>